package com.scs.application.modules.wm.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.wm.entity.OprtCheckItem;
import com.scs.application.modules.wm.service.OprtCheckItemService;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 */
@RestController
@RequestMapping("/wm/oprt_check_item")
public class OprtCheckItemController extends CrudController<OprtCheckItemService, OprtCheckItem>{

    @PostMapping("/addCheckItem")
    public RestResult addCheckItem(@RequestBody Map<String, String> para) {
        service.addCheckItem(para.get("checkId"), para.get("prepareId"));
        return RestResult.ok("数据保存成功");
    }

    @PostMapping("/updateSpQty")
    public RestResult updateSpQty(@RequestBody Map<String, String> para) {
        service.updateSpQty(para);
        return RestResult.ok("数量已更新");
    }


    @Override
    @GetMapping("/page")
    public PageResult page() {
        QueryContext queryContext = QueryContextHolder.currentContext();
        Page<OprtCheckItem> page = (Page<OprtCheckItem>) service.page(queryContext);
        this.fillDataPage(page);
        return PageResult.ok("查询成功", page.getRecords() , page.getTotal());
    }

    private void fillDataPage (Page<OprtCheckItem> page ) {
        if (page.getRecords() == null || page.getRecords().size() == 0) {
            return;
        }
        List<OprtCheckItem> itemList = page.getRecords();

        // 包
        List<OprtCheckItem> itemPackList = itemList.stream().filter(item -> StringUtils.isNotBlank(item.getPackId())).collect(Collectors.toList());
        if (ObjectUtil.length(itemPackList) == 0) {
            return;
        }
        List<OprtCheckItem> itemListNew = new ArrayList<>();
        List<OprtCheckItem> itemChildList= null;
        int index = 0;
        for(OprtCheckItem packItem : itemPackList) {
            itemListNew.add(packItem);
            itemChildList = itemList.stream().filter(item -> packItem.getId().equals(item.getPackCheckItemId())).collect(Collectors.toList());
            if (!itemChildList.isEmpty()) {
                itemListNew.addAll(itemChildList);
            }
        }
        page.setRecords(itemListNew);
    }

}
